<!--
 * @Author: dengyl
 * @Date: 2022-01-11 19:54:15
 * @LastEditTime: 2022-08-25 22:26:28
 * @LastEditors: 詹真琦(legendryztachi@gmail.com)
 * @Description: 新闻-轮播图
 * @FilePath: \code\ctp-static-portal-front\src\components\news\components\slideshow.vue
-->
<template>
  <div class="slideshow" :style="divStyle" ref="textImg">
    <div :id="swiperId" class="swiper-container">
      <div class="swiper-wrapper image-view" :class="[imageStyle]">
        <template v-if="currentImages.length">
          <div
            v-for="item in currentImages"
            :key="item.id"
            ref="imgItem"
            class="swiper-slide swiper-no-swiping img-item"
          >
            <a :href="`${newsBasePath}${item.link}`" target="_blank">
              <ShowImg :item="item" />
              <span v-if="!direction" class="title"
                ><span>{{ item.subject }}</span></span
              >
            </a>
          </div>
        </template>
      </div>
      <!-- 竖版 -->
      <div v-if="direction" class="text-column">
        <div class="title-column" v-if="currentImages.length">
          <div
            :title="titleItem.subject"
            v-for="(titleItem, index) in currentImages"
            :key="index"
            ref="title"
            :class="['title-item', [index == activeIndex ? 'title-active' : '']]"
            @click="handleTitle(index)"
            ><div>{{ titleItem.subject }}</div>
          </div>
        </div>
      </div>
      <template v-if="!direction">
        <div class="pagination"></div>
        <div class="control-btn left-btn" @click="handleLeft">
          <span>&lt;</span>
        </div>
        <div class="control-btn right-btn" @click="handleRight">
          <span> &gt;</span>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
  import { rowList, image } from '@/mixins';
  import swiper from '@/mixins/swiper';
  import emitter from '@/utils/global';
  export default {
    name: 'Slideshow',
    mixins: [rowList, image, swiper],
    props: {
      direction: {
        type: Boolean,
        default: false //true:竖版；false：横版
      },
      list: { type: Array },
      options: { type: Object }
    },
    data() {
      return {
        newsBasePath: `${_basePath}/`,
        currentImages: [],
        // textImgBoxHeight: null,
        activeIndex: 0,
        swiperId: `swiper${this._uid}`
      };
    },
    computed: {
      playSpeed() {
        switch (this.options.speed) {
          case 'speed1':
            return 1000;
          case 'speed3':
            return 5000;
          default:
            return 3000;
        }
      },
      divStyle() {
        return {
          'background-color': this.options.backgroundColor
          //height: `${this.options.options.height}px`,
        };
      }
    },
    created() {
      const count = this.direction ? 3 : +this.options.count || this.sectionData.data.dataNum;
      this.currentImages = this.list?.slice(0, count) || [];
      emitter.subscribe('resizeFinished', () => {
        this._swiper && this._swiper.resizeFix();
        this.initImage(true);
      });
      // fixme: 显示图片个数
      // if (this.direction == 'true') {
      //     this.currentImages = this.images?.slice(0, count) || [];
      // } else {

      //     // this.currentImages = this.images.slice(0, +this.options.rows.dataNum);
      // }
    },
    mounted() {
      // console.log('***************8')
      // console.log(`this.options.options.rowList: ${this.options}`, this.options)
      // console.log('***************8')
      // this.setImageBoxSize();
      this.initSwiper();
    },

    methods: {
      /**
       * @description:设置图文盒子大小
       */
      // setImageBoxSize() {
      //     this.titleBox = this.$refs.title;
      //     this.textImgBoxHeight = this.$refs.textImg.clientHeight;
      //     if (this.direction == 'true') {
      //         this.titleBox?.forEach((item) => {
      //             item.style.height = +this.textImgBoxHeight / 3 + 'px';
      //         });
      //     }
      // },
      /**
       * @description 初始化swiper
       */
      initSwiper() {
        if (this.direction) {
          this.setSwiper(
            new Swiper(`#${this.swiperId}`, {
              loop: true,
              autoplay: this.playSpeed,
              speed: 300,
              autoplayDisableOnInteraction: false,
              mode: 'vertical',
              paginationClickable: false,
              createPagination: false,
              noSwiping: true,
              // 动画的时候回调函数
              onSlideChangeEnd: function (swiper) {
                // console.log(swiper,swiper.activeIndex);
                // if (swiper.activeIndex > 2) {
                //     this.activeIndex = 0;
                // } else {
                this.activeIndex = swiper.activeLoopIndex;
                // }
              }.bind(this),
              onAutoplayStop: function (swiper) {
                if (!swiper.support.transitions) {
                  //IE7、IE8
                  swiper.startAutoplay();
                }
              },
              onFirstInit: () => {
                this.initImage();
              }
            })
          );
          // this.activeIndex = this._swiper.activeIndex - 1;
        } else {
          this.setSwiper(
            new Swiper(`#${this.swiperId}`, {
              loop: true,
              autoplay: this.playSpeed,
              speed: 300,
              autoplayDisableOnInteraction: false,
              mode: 'horizontal',
              pagination: `#${this.swiperId}>.pagination`,
              paginationClickable: true,
              createPagination: true,
              // noSwiping : true,
              onAutoplayStop: function (swiper) {
                if (!swiper.support.transitions) {
                  //IE7、IE8
                  swiper.startAutoplay();
                }
              },
              onFirstInit: () => {
                this.initImage();
              }
            })
          );
        }
      },

      /**
       * @description 向左调幻灯片
       */
      handleLeft() {
        this._swiper.swipePrev();
        // console.log();
      },
      /**
       * @description 向右调幻灯片
       */
      handleRight() {
        this._swiper.swipeNext();
      },
      /**
       * 竖版切幻灯片
       */
      handleTitle(index) {
        this._swiper.swipeTo(index, 300, false);
        this.activeIndex = this._swiper.activeIndex - 1;
      },
      initImage(isNotFirst = false) {
        $.each($(`#${this.swiperId} .show-image`), (i, target) => {
          const { width, height } = target;
          const { offsetWidth, offsetHeight } = target.parentNode;
          //子元素（图片）比例大于父元素（框）contain使用宽撑满
          if (width / height > offsetWidth / offsetHeight) {
            target.className += ' contain-width cover-height';
          } else {
            //不是第一次，就要去掉class
            if (isNotFirst) {
              $(target).removeClass('contain-width cover-height');
            }
          }
        });
      }
    }
  };
</script>
<style lang="scss" scoped>
  * {
    padding: 0;
    margin: 0;
    list-style: none;
    box-sizing: border-box;
  }

  .slideshow {
    // width: 100%;
    // width: 300px;
    height: 100%;
    overflow: hidden;
    // border: 1px solid green;
    border-radius: 10px;
  }

  .swiper-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
    // border: 1px solid red;
    &:hover {
      .control-btn {
        display: block;
      }
    }

    // .swiper-wrapper {
    //   width: 100%;
    //   height: 100%;
    // }

    .img-item {
      position: relative;
      height: 100%;

      a {
        display: block;
        height: 100%;
        overflow: hidden;
        text-align: center;
        border-radius: 10px;
      }

      .title {
        position: absolute;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 999;
        height: 30px;
        padding-left: 10px;
        font-size: 14px;
        line-height: 30px;
        color: #fff;
        text-align: left;
        background-color: rgba(0, 0, 0, 0.5);
        filter: progid:dximagetransform.microsoft.gradient(startColorstr=#7f000000,endColorstr=#7f000000);
      }
    }
  }

  .pagination {
    position: absolute;
    right: 10px;
    bottom: 0;
    z-index: 999;
    height: 30px;
    text-align: center;
  }

  .control-btn {
    position: absolute;
    top: 50%;
    z-index: 10;
    display: none;
    width: 50px;
    height: 50px;
    margin-top: -25px;
    font-size: 22px;
    line-height: 50px;
    color: #fff;
    text-align: center;
    cursor: pointer;
    background-color: rgba(0, 0, 0, 0.15);
    border-radius: 50%;
  }

  .left-btn {
    left: 30px;
  }

  .right-btn {
    right: 30px;
  }

  .text-column {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    width: 150px;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.5);
    // 兼容ie8点击切换时穿透问题
    background-image: url(about:blank);
    filter: progid:dximagetransform.microsoft.gradient(startColorstr=#7f000000,endColorstr=#7f000000);

    > .title-column {
      height: 100%;

      > div {
        height: 33.333%;
      }
    }
  }

  .title-item {
    z-index: 9999;
    padding: 10px 15px;
    cursor: pointer;

    > div {
      display: -webkit-box;
      height: 90%;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: break-all;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3;
    }
  }

  .title-active {
    position: relative;
    background-color: rgba(0, 0, 0, 0.5);
    border-bottom-left-radius: 10px;
    border-top-left-radius: 10px;
    filter: progid:dximagetransform.microsoft.gradient(startColorstr=#7f000000,endColorstr=#7f000000);
  }

  .title-active::before {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    z-index: 99999;
    width: 5px;
    background-color: #2490f8;
    border-bottom-left-radius: 10px;
    border-top-left-radius: 10px;
    content: '';
  }
</style>
<style>
  .swiper-pagination-switch {
    display: inline-block;
    width: 10px;
    height: 10px;
    margin-left: 10px;
    cursor: pointer;
    background-color: rgba(255, 255, 255, 0.5);
    border-radius: 50%;
  }

  .swiper-active-switch {
    width: 20px;
    height: 10px;
    background-color: #2490f8;
    border-radius: 10px;
  }
</style>
